// 14.最长公共前缀
package Leetcode_Second_Brush;

public class Solution014 {
    public String longestCommonPrefix1(String[] strs) {
        int minLength = Integer.MAX_VALUE;
        for (int i = 0; i < strs.length; i++) {
            if (strs[i].length() < minLength)
                minLength = strs[i].length();
        }

        StringBuilder result = new StringBuilder();

        for (int i = 0; i < minLength; i++) {
            char c = strs[0].charAt(i);
            for (int j = 1; j < strs.length; j++) {
                if (strs[j].charAt(i) != c)
                    return result.toString();
            }
            result.append(c);
        }

        return result.toString();
    }

    public String longestCommonPrefix(String[] strs) {
        // 剪枝
        if (strs == null || strs.length == 0) {
            return "";
        }

        // 外循环为 strs[0] 的长度，它不一定是最短的
        for (int i = 0; i < strs[0].length(); i++) {
            char c = strs[0].charAt(i);  //取出 strs[0] 的第 i 个字符
            // 内循环遍历后续每个字符串
            for (int j = 1; j < strs.length; j++) {
                // 如果字符串长度不够，或者字符不相等，表示最长前缀到此为止
                if (i == strs[j].length() || strs[j].charAt(i) != c) {
                    return strs[0].substring(0, i);
                }
            }
        }
        
        // 如果 strs[0] 正好为最长前缀
        return strs[0];
    }

}
